package com.party.mobile.web.controller;


import com.google.gson.Gson;
import com.party.authorization.annotation.Authorization;
import com.party.authorization.manager.impl.RedisTokenManager;
import com.party.common.utils.FileUtils;
import com.party.common.utils.PinyinUtil;
import com.party.core.model.activity.Activity;
import com.party.core.model.city.Area;
import com.party.core.model.crowdfund.CrowdfundEvent;
import com.party.core.model.crowdfund.Project;
import com.party.core.model.crowdfund.Support;
import com.party.core.model.crowdfund.TargetProject;
import com.party.core.model.member.*;
import com.party.core.model.order.OrderForm;
import com.party.core.model.order.OrderType;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.city.IAreaService;
import com.party.core.service.city.ICityService;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.crowdfund.ICrowdfundEventService;
import com.party.core.service.crowdfund.IProjectService;
import com.party.core.service.crowdfund.ISupportService;
import com.party.core.service.crowdfund.ITargetProjectService;
import com.party.core.service.member.*;
import com.party.core.service.notify.IInstanceService;
import com.party.core.service.order.IOrderFormService;
import com.party.mobile.biz.activity.MemberActBizService;
import com.party.mobile.biz.crowdfund.PaintProjectPosterBiz;
import com.party.mobile.biz.crowdfund.ProjectBizService;
import com.party.mobile.biz.file.FileBizService;
import com.party.mobile.biz.order.MessageOrderBizService;
import com.party.mobile.biz.order.OrderBizService;
import com.party.mobile.web.dto.AjaxResult;
import com.party.mobile.web.dto.crowdfund.output.ProjectPosterOutput;
import com.party.notify.notifyPush.servce.INotifySendService;
import com.party.notify.wechatNotify.service.impl.WechatNotifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;


/**
 * party
 * Created by wei.li
 * on 2016/9/20 0020.
 */
@Controller
@RequestMapping("/mobile")
public class TestController {

    @Autowired
    IMemberService memberService;

    @Autowired
    IAreaService areaService;
    @Autowired
    IIndustryService industryService;

    @Autowired
    IActivityService activityService;

    @Autowired
    ICityService cityService;

    @Autowired
    RedisTokenManager redisTokenManager;

    @Autowired
    IProjectService projectService;

    @Autowired
    IOrderFormService orderFormService;

    @Autowired
    OrderBizService orderBizService;

    @Autowired
    INotifySendService notifySendService;

    @Autowired
    MessageOrderBizService messageOrderBizService;

    @Autowired
    IInstanceService instanceService;

    @Autowired
    MessageOrderBizService service;

    @Autowired
    WechatNotifyService wechatNotifyService;

    @Autowired
    private PaintProjectPosterBiz paintProjectPosterBiz;

    @Autowired
    private ProjectBizService projectBizService;

    @Autowired
    private ISupportService supportService;

    @Autowired
    private ICrowdfundEventService crowdfundEventService;

    @Autowired
    private MemberActBizService memberActBizService;

    @Autowired
    private ITargetProjectService targetProjectService;

    @Autowired
    private IMemberGroupService memberGroupService;

    @ResponseBody
    @RequestMapping("/updateAreaPinyin")
    public AjaxResult updateAreaPinyin(String projectId) {
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setSuccess(true);
        List<Area> areas = areaService.listAll();
        for (Area area : areas) {
            area.setPinyin(PinyinUtil.hanziToPinyin(area.getName(), ""));
            areaService.update(area);
        }
        return ajaxResult;
    }

    @ResponseBody
    @RequestMapping("/updateIndustryPinyin")
    public AjaxResult updateIndustryPinyin() {
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setSuccess(true);
        List<Industry> industries = industryService.listAll();
        for (Industry industry : industries) {
            industry.setPinyin(PinyinUtil.hanziToPinyin(industry.getName(), ""));
            industryService.update(industry);
        }
        return ajaxResult;
    }

    @ResponseBody
    @RequestMapping("/mm")
    public AjaxResult test1() {
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setSuccess(true);

        redisTokenManager.createRelationship("key", "token");

        String key = redisTokenManager.getKey("token");

        ajaxResult.setData(key);
        return ajaxResult;
    }


    @ResponseBody
    @RequestMapping("/m")
    public AjaxResult test() {
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setSuccess(true);
        OrderForm orderForm = orderFormService.get("e0aa453b1f714c22873a0164ae479a27");
        Project project = projectService.get("77cd9c54705e49d7bf696834fa6af61c");
        Member member = memberService.get("71080f2503d44867ad1ec27f7487915a");
//        notifySendService.sendProjectStage(project, member, 10, 10);
        return ajaxResult;
    }

    @ResponseBody
    @RequestMapping("/testPayReset")
    public AjaxResult testPayReset(String orderId) {
        try {
            OrderForm orderForm = orderFormService.get(orderId);
            if (OrderType.ORDER_ACTIVITY.getCode().equals(orderForm.getType())) {
                memberActBizService.testPayReset(orderId);
            } else if (OrderType.ORDER_CROWD_FUND.getCode().equals(orderForm.getType())) {
                projectBizService.testPayReset(orderId);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(100, "失败");
        }

    }

    @ResponseBody
    @RequestMapping("/h")
    @Authorization
    public ResponseEntity<String> home() {
        return new ResponseEntity<>("Hello World", HttpStatus.OK);
    }

    @RequestMapping("/testt")
    @ResponseBody
    public String testtt() {
        OrderForm f = new Gson().fromJson("{\"delFlag\":\"0\",\"goodsId\":\"e2b2a54ce287443686779ee7efe4e712\"," +
                "\"id\":\"0c184adc784d4692b0a9286b3cc4afd5\",\"initiatorId\":\"a495e691c6d545f1b838f25218393008\"," +
                "\"isPay\":\"1\",\"memberId\":\"62cf51dfca854376be1c7d25b83642d1\",\"merchantId\":\"1371766102\"," +
                "\"merchantName\":\"同行者俱乐部\",\"payment\":0.01,\"paymentWay\":1,\"phone\":\"18723197783\"," +
                "\"sort\":0,\"status\":2,\"title\":\"test35no众筹--001\",\"tradeType\":\"wx_wwz\",\"type\":3,\"unit\":1}", OrderForm.class);
        Project p = projectService.get("e2b2a54ce287443686779ee7efe4e712");

//        service.supportWechatSend(f, p);
        return "haha";
    }

    @RequestMapping("/hqhtest")
    @ResponseBody
    public void hqhtest() throws Exception {
        byte[] bytes = new byte[1024];
        String pahturl = paintProjectPosterBiz.getXmlPath() + "image\\raisePostersImg\\" + "123" + ".png";
        File pfile = new File(pahturl);
        FileUtils.writeByteArrayToFile(pfile, bytes);
        pfile.delete();
        // pfile.delete();
        //wechatNotifyService.customerServiceSend("osScduL5W7gX8sdH-6KDog2WKGkI","image","12_gxDKzsMWaTfgstz3m0KNgcfBBlkCzPpamjlFV9z9hEX3VTD1yMT_y-2NEXe6x2gdof1WncxAhCmppCpulNI3Lez8tIlJhl_1Mp1OtOaT8-LelqMPIaO_t8lIsJylNnUm-PzXbyKZQcbZ3COFHTPjADADPL",new File("D:\\Project\\party-mobile\\src\\main\\webapp\\img\\test1.png"));
    }

    @ResponseBody
    @RequestMapping("paintSupportPoster")
    public AjaxResult paintSupportPoster(String supportId) {
        long start = System.currentTimeMillis();
        Support support = supportService.get(supportId);
        OrderForm orderForm = orderFormService.get(support.getOrderId());
        String projectId = support.getProjectId();
        TargetProject targetProject = targetProjectService.findByProjectId(projectId);
        Activity activity = activityService.get(targetProject.getTargetId());
        Project project = projectService.get(projectId);
        Member crowdfundMember = memberService.get(project.getAuthorId());
        MemberGroup orgMember = memberGroupService.get(activity.getMember());
        Member supportMember = memberService.get(support.getFavorerId());
        messageOrderBizService.supportersPostersSend(projectId, orderForm.getMemberId(), activity.getMember(),
                orderForm.getPayment().toString(), crowdfundMember, orgMember, activity, supportMember);
        long end = System.currentTimeMillis();
        System.out.println(end - start);
        return AjaxResult.success();
        /*try {
            Support support1 = new Support();
            support1.setProjectId(projectId);
            List<Support> supports = supportService.listPage(support1, new Page(0, 1000));
            for (Support support : supports) {
                try {
                    OrderForm orderForm = orderFormService.get(support.getOrderId());
                    Double payment = null == orderForm ? 10086.88 : orderForm.getPayment();
                    double round = BigDecimalUtils.round(payment, 2);
                    String money = round + "";
                    projectId = support.getProjectId();
                    byte[] bytes = projectBizService.paintSupportersPoster(projectId, support.getFavorerId(), money);
//            byte[] bytes = projectBizService.paintProjectPoster(projectId);
                    OutputStream outputStream = new FileOutputStream(new File(paintProjectPosterBiz.getXmlPath() + "image" + File.separator + "raisePostersImg" + File.separator + support.getId() + ".png"));
                    outputStream.write(bytes);
                    outputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
            }
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(100, "绘制海报异常");
        }*/
    }

    @ResponseBody
    @RequestMapping("paintProjectPoster")
    public AjaxResult paintProjectPoster(String projectId, Integer limit, Integer page) {
        long start = System.currentTimeMillis();
        TargetProject targetProject = targetProjectService.findByProjectId(projectId);
        Activity activity = activityService.get(targetProject.getTargetId());
        Project project = projectService.get(projectId);
        Member crowdfundMember = memberService.get(project.getAuthorId());
        MemberGroup orgMember = memberGroupService.get(activity.getMember());
        messageOrderBizService.raiseSuccessfulPostersSend(project.getId(), project.getAuthorId(), activity.getMember(),
                crowdfundMember, orgMember, activity);
        long end = System.currentTimeMillis();
        System.out.println(end - start);
        return AjaxResult.success();
        /*if (null == page) {
            return AjaxResult.error(100, "请输入page参数");
        }
        if (null == limit) {
            return AjaxResult.error(100, "请输入limit参数");
        }
        try {
            Project p = new Project();
            p.setId(projectId);
            List<Project> projects = projectService.listPage(p, new Page(page, limit));
            for (Project project : projects) {
                try {
                    byte[] bytes = projectBizService.paintProjectPoster(project.getId());
                    OutputStream outputStream = new FileOutputStream(new File(paintProjectPosterBiz.getXmlPath() + "image" + File.separator + "raisePostersImg" + File.separator + project.getId() + ".png"));
                    outputStream.write(bytes);
                    outputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
            }
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(100, "绘制海报异常");
        }*/
    }

    @Autowired
    private FileBizService fileBizService;
    @Autowired
    private CosBizService cosBizService;

    @ResponseBody
    @RequestMapping("paintNewYearPoster")
    public AjaxResult paintNewYearPoster(String projectId) {
        try {
            byte[] bytes = null;
            Project project = projectService.get(projectId);
            Member member = memberService.get(project.getAuthorId());
            CrowdfundEvent crowdfundEvent = crowdfundEventService.findByProjectId(project.getId());
            if (null == project) {
                return AjaxResult.error(100, "项目不存在");
            }

            ProjectPosterOutput posterOutput = new ProjectPosterOutput();
            posterOutput.setLogo(member.getLogo());
            posterOutput.setProjectId(projectId);
            posterOutput.setAuthorId(member.getId());
            posterOutput.setNetworkImagePath(crowdfundEvent.getNetworkImagePath());
            //*** 个人众筹项目详情二维码 ***//*
            String filePath = fileBizService.getUploadCIPath("crowdfund", posterOutput.getAuthorId());
            String qrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + posterOutput.getProjectId());
            posterOutput.setPersonalQrCodeUrl(qrCodeUrl);

            bytes = paintProjectPosterBiz.newYearPoster(posterOutput);

            OutputStream outputStream = new FileOutputStream(new File(paintProjectPosterBiz.getXmlPath() + "image" + File.separator + "raisePostersImg" + File.separator + projectId + ".png"));
            outputStream.write(bytes);
            outputStream.close();


            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(100, "绘制海报异常");
        }
    }

    @Autowired
    private IPosterTmpOrg posterTmpOrg;

    @Autowired
    private IPosterTmpProject posterTmpProject;

    @ResponseBody
    @RequestMapping("blessingFontPoster")
    public AjaxResult blessingFontPoster(String projectId) {
        try {
            List<PosterTmpOrg> ptolist = posterTmpOrg.listPage(null, null);


            for (PosterTmpOrg ptoObj : ptolist) {
                File file = new File(paintProjectPosterBiz.getXmlPath() + "image" + File.separator + "raisePostersImg/" + ptoObj.getOrgName());
                if (!file.exists()) {
                    file.mkdir();
                }
                byte[] bytes = null;
                HashMap<Object, Object> mmp = new HashMap<>();
                mmp.put("zeCreateBy", ptoObj.getId());
                mmp.put("GROUP", 0);
                List<PosterTmpProject> ptplist = posterTmpProject.outList(null, mmp);

                for (PosterTmpProject ptpObj : ptplist) {
                    String zepath = paintProjectPosterBiz.getXmlPath() + "image" + File.separator + "raisePostersImg/" + ptoObj.getOrgName() + "/" + ptpObj.getZeTile();
                    File file_ze = new File(zepath);
                    if (!file_ze.exists()) {
                        file_ze.mkdir();
                    }

                    HashMap<Object, Object> project_mmp = new HashMap<>();
                    project_mmp.put("zeId", ptpObj.getZeId());


                    List<PosterTmpProject> posterTmpProjectList= posterTmpProject.outList(null,project_mmp);

                    for (PosterTmpProject posterTmpProject :posterTmpProjectList){
                        ProjectPosterOutput posterOutput = new ProjectPosterOutput();
                        posterOutput.setLogo(posterTmpProject.getMemberUserlogo());
                        posterOutput.setProjectId(posterTmpProject.getId());
                        posterOutput.setAuthorId(posterTmpProject.getMemberId());
                        posterOutput.setNickName(posterTmpProject.getMemberUsername());
                        posterOutput.setLogo(posterTmpProject.getMemberUserlogo());
                        try {

                            //*** 个人众筹项目详情二维码 ***//*
                            String filePath = fileBizService.getUploadCIPath("crowdfund", posterOutput.getAuthorId());
                            String qrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + posterOutput.getProjectId());
                            posterOutput.setPersonalQrCodeUrl(qrCodeUrl);

                            bytes = paintProjectPosterBiz.blessingFontPoster(posterOutput);

                            String nickName =posterOutput.getNickName();


                            Pattern FilePattern = Pattern.compile("[\\\\/:*?\"<>|]");
                            nickName= FilePattern.matcher(nickName).replaceAll("");
                            posterOutput.setNickName(nickName);

                            String imgpath=zepath+File.separator + posterOutput.getNickName()+".png";



                            File imgFile = new File(imgpath);
                            if(imgFile.exists()){
                                imgFile=new File(zepath+File.separator  +posterOutput.getNickName()+"1"+".png");
                            }
                            if(imgFile.exists()){
                                imgFile=new File(zepath+File.separator + posterOutput.getNickName()+"2"+".png");
                            }
                            if(imgFile.exists()){
                                imgFile=new File(zepath+File.separator + posterOutput.getNickName()+"3"+".png");
                            }

                            OutputStream outputStream = new FileOutputStream(imgFile);
                            outputStream.write(bytes);
                            outputStream.close();
                        }catch (Exception ee){
                            System.out.println("个人二维码异常");
                            //生成众筹详情二维码异个人二维码
                            try {
                                String filePath = fileBizService.getUploadCIPath("crowdfund", posterOutput.getAuthorId());
                                String content = "project/project_detail.html?id=" + posterOutput.getProjectId();
                                String previewPicUrl = fileBizService.uploadCloudOut(posterOutput.getProjectId(), filePath, content, posterOutput.getAuthorId());
                                if (previewPicUrl == null) {
                                    System.out.println("生成众筹详情二维码异个人二维码");

                                }
                            } catch (Exception e2) {
                                System.out.println("生成众筹详情二维码异个人二维码"+e2.getMessage());

                            }
                        }

                    }
                    System.out.println("第一个主题结束");
                }

            }

            return AjaxResult.success();
        } catch (Exception e) {

            e.printStackTrace();
            return AjaxResult.error(100, "绘制海报异常");
        }
    }
}
